import { defineStore } from 'pinia'
import { ElMessage } from 'element-plus'
import * as api from '../api/index.js'

// 用户Store
export const useUserStore = defineStore('user', {
  state: () => ({
    userInfo: JSON.parse(localStorage.getItem('userInfo') || '{}'),
    token: localStorage.getItem('token') || '',
    isLoading: false,
    addresses: [],
    favorites: [],
    error: null
  }),
  
  getters: {
    isLoggedIn: (state) => !!state.token,
    isAdmin: (state) => state.userInfo.role === 'admin',
    displayName: (state) => state.userInfo.username || '未登录',
    avatar: (state) => state.userInfo.avatar || 'https://via.placeholder.com/40'
  },
  
  actions: {
    async login(credentials) {
      this.isLoading = true
      this.error = null
      try {
        const response = await api.login(credentials)
        const { token, userInfo } = response.data
        this.token = token
        this.userInfo = userInfo
        localStorage.setItem('token', token)
        localStorage.setItem('userInfo', JSON.stringify(userInfo))
        ElMessage.success('登录成功')
        return response.data
      } catch (error) {
        this.error = error.message
        ElMessage.error('登录失败：' + (error.message || '未知错误'))
        throw error
      } finally {
        this.isLoading = false
      }
    },
    
    async register(userData) {
      this.isLoading = true
      this.error = null
      try {
        const response = await api.register(userData)
        ElMessage.success('注册成功，请登录')
        return response.data
      } catch (error) {
        this.error = error.message
        ElMessage.error('注册失败：' + (error.message || '未知错误'))
        throw error
      } finally {
        this.isLoading = false
      }
    },
    
    async updateProfile(profileData) {
      try {
        const response = await api.updateUserInfo(profileData)
        this.userInfo = response.data
        localStorage.setItem('userInfo', JSON.stringify(response.data))
        ElMessage.success('个人信息更新成功')
        return response.data
      } catch (error) {
        ElMessage.error('更新失败：' + (error.message || '未知错误'))
        throw error
      }
    },
    
    async loadUserInfo() {
      if (!this.token) return
      try {
        const response = await api.getUserInfo()
        this.userInfo = response.data
        localStorage.setItem('userInfo', JSON.stringify(response.data))
      } catch (error) {
        // 如果获取用户信息失败，可能是token过期，清除登录状态
        this.logout()
      }
    },
    
    async loadAddresses() {
      if (!this.token) return
      try {
        const response = await api.getUserAddresses()
        this.addresses = response.data
      } catch (error) {
        ElMessage.error('获取地址列表失败')
      }
    },
    
    async loadFavorites() {
      if (!this.token) return
      try {
        const response = await api.getUserFavorites({ page: 1, pageSize: 100 })
        this.favorites = response.data.list || []
      } catch (error) {
        ElMessage.error('获取收藏列表失败')
      }
    },
    
    logout() {
      this.token = ''
      this.userInfo = {}
      this.addresses = []
      this.favorites = []
      this.error = null
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      ElMessage.info('已退出登录')
    }
  }
})

// 商品Store
export const useProductStore = defineStore('product', {
  state: () => ({
    products: [],
    currentProduct: null,
    categories: [],
    hotProducts: [],
    recommendedProducts: [],
    searchHistory: JSON.parse(localStorage.getItem('searchHistory') || '[]'),
    isLoading: false,
    total: 0,
    error: null
  }),
  
  getters: {
    productById: (state) => (id) => {
      return state.products.find(p => p.id === Number(id)) || state.currentProduct
    },
    categoryById: (state) => (id) => {
      return state.categories.find(c => c.id === Number(id))
    },
    searchHistoryLimited: (state) => {
      return state.searchHistory.slice(0, 10) // 最多保存10条搜索历史
    }
  },
  
  actions: {
    async getProducts(params = {}) {
      this.isLoading = true
      this.error = null
      try {
        const response = await api.getProductList(params)
        this.products = response.data.list || []
        this.total = response.data.total || 0
        return response.data
      } catch (error) {
        this.error = error.message
        ElMessage.error('获取商品列表失败')
        throw error
      } finally {
        this.isLoading = false
      }
    },
    
    async getProductById(id) {
      this.isLoading = true
      try {
        const response = await api.getProductDetail(id)
        this.currentProduct = response.data
        return response.data
      } catch (error) {
        ElMessage.error('获取商品详情失败')
        throw error
      } finally {
        this.isLoading = false
      }
    },
    
    async createProduct(productData) {
      try {
        const response = await api.publishProduct(productData)
        ElMessage.success('商品发布成功')
        return response.data
      } catch (error) {
        ElMessage.error('商品发布失败')
        throw error
      }
    },
    
    async updateProduct(id, productData) {
      try {
        const response = await api.updateProduct(id, productData)
        ElMessage.success('商品更新成功')
        return response.data
      } catch (error) {
        ElMessage.error('商品更新失败')
        throw error
      }
    },
    
    async deleteProduct(id) {
      try {
        const response = await api.deleteProduct(id)
        // 从本地列表中移除
        this.products = this.products.filter(p => p.id !== Number(id))
        ElMessage.success('商品删除成功')
        return response.data
      } catch (error) {
        ElMessage.error('商品删除失败')
        throw error
      }
    },
    
    async getCategories() {
      try {
        const response = await api.getProductCategories()
        this.categories = response.data || []
        return response.data
      } catch (error) {
        ElMessage.error('获取商品分类失败')
        throw error
      }
    },
    
    async getHotProducts(limit = 10) {
      try {
        const response = await api.getHotProducts(limit)
        this.hotProducts = response.data || []
        return response.data
      } catch (error) {
        console.error('获取热门商品失败', error)
        return []
      }
    },
    
    async getRecommendedProducts(params = {}) {
      try {
        const response = await api.getRecommendedProducts(params)
        this.recommendedProducts = response.data || []
        return response.data
      } catch (error) {
        console.error('获取推荐商品失败', error)
        return []
      }
    },
    
    addSearchHistory(keyword) {
      if (!keyword || keyword.trim() === '') return
      
      // 移除重复项
      this.searchHistory = this.searchHistory.filter(item => item !== keyword)
      // 添加到开头
      this.searchHistory.unshift(keyword)
      // 限制数量
      this.searchHistory = this.searchHistory.slice(0, 10)
      // 保存到localStorage
      localStorage.setItem('searchHistory', JSON.stringify(this.searchHistory))
    },
    
    clearSearchHistory() {
      this.searchHistory = []
      localStorage.removeItem('searchHistory')
    }
  }
})

// 购物车Store
export const useCartStore = defineStore('cart', {
  state: () => ({
    items: JSON.parse(localStorage.getItem('cartItems') || '[]'),
    selectedItems: JSON.parse(localStorage.getItem('selectedCartItems') || '[]')
  }),
  
  getters: {
    totalPrice: (state) => {
      return state.items.reduce((total, item) => total + item.price * item.quantity, 0)
    },
    totalCount: (state) => {
      return state.items.reduce((total, item) => total + item.quantity, 0)
    },
    selectedItemsList: (state) => {
      return state.items.filter(item => state.selectedItems.includes(item.id))
    },
    selectedTotalPrice: (state) => {
      return state.items
        .filter(item => state.selectedItems.includes(item.id))
        .reduce((total, item) => total + item.price * item.quantity, 0)
    },
    selectedCount: (state) => {
      return state.items
        .filter(item => state.selectedItems.includes(item.id))
        .reduce((total, item) => total + item.quantity, 0)
    },
    isAllSelected: (state) => {
      return state.items.length > 0 && state.items.every(item => state.selectedItems.includes(item.id))
    }
  },
  
  actions: {
    addToCart(product, quantity = 1) {
      if (!product || !product.id) {
        ElMessage.warning('商品信息无效')
        return
      }
      
      const existingItem = this.items.find(item => item.id === product.id)
      if (existingItem) {
        existingItem.quantity += quantity
        ElMessage.success(`商品数量已更新为 ${existingItem.quantity}`)
      } else {
        // 只保存必要的字段
        const cartItem = {
          id: product.id,
          title: product.title,
          price: product.price,
          originalPrice: product.originalPrice,
          images: product.images,
          quantity: quantity,
          status: product.status || 'approved'
        }
        this.items.push(cartItem)
        ElMessage.success('已添加到购物车')
      }
      this.saveToStorage()
    },
    
    removeFromCart(productId) {
      const itemIndex = this.items.findIndex(item => item.id === productId)
      if (itemIndex !== -1) {
        this.items.splice(itemIndex, 1)
        // 同时从选中列表中移除
        this.selectedItems = this.selectedItems.filter(id => id !== productId)
        ElMessage.success('已从购物车移除')
        this.saveToStorage()
      }
    },
    
    updateQuantity(productId, quantity) {
      const item = this.items.find(item => item.id === productId)
      if (item) {
        // 确保数量为正整数
        const newQuantity = Math.max(1, Math.floor(Number(quantity) || 1))
        item.quantity = newQuantity
        this.saveToStorage()
      }
    },
    
    selectItem(productId, isSelected) {
      if (isSelected) {
        if (!this.selectedItems.includes(productId)) {
          this.selectedItems.push(productId)
        }
      } else {
        this.selectedItems = this.selectedItems.filter(id => id !== productId)
      }
      localStorage.setItem('selectedCartItems', JSON.stringify(this.selectedItems))
    },
    
    selectAll(isSelected) {
      if (isSelected) {
        this.selectedItems = this.items.map(item => item.id)
      } else {
        this.selectedItems = []
      }
      localStorage.setItem('selectedCartItems', JSON.stringify(this.selectedItems))
    },
    
    clearCart() {
      this.items = []
      this.selectedItems = []
      this.saveToStorage()
    },
    
    removeSelectedItems() {
      this.items = this.items.filter(item => !this.selectedItems.includes(item.id))
      this.selectedItems = []
      this.saveToStorage()
      ElMessage.success('已移除选中商品')
    },
    
    saveToStorage() {
      localStorage.setItem('cartItems', JSON.stringify(this.items))
      localStorage.setItem('selectedCartItems', JSON.stringify(this.selectedItems))
    },
    
    // 检查商品是否仍然有效
    validateCartItems() {
      // 这里可以添加逻辑检查商品是否下架或价格变动
      this.items = this.items.filter(item => item.status === 'approved')
      this.saveToStorage()
    }
  }
})

// 订单Store
export const useOrderStore = defineStore('order', {
  state: () => ({
    orders: [],
    sellerOrders: [],
    currentOrder: null,
    isLoading: false,
    error: null
  }),
  
  getters: {
    orderById: (state) => (id) => {
      return state.orders.find(o => o.id === id) || 
             state.sellerOrders.find(o => o.id === id) || 
             state.currentOrder
    },
    ordersByStatus: (state) => (status) => {
      return state.orders.filter(o => o.status === status)
    },
    // 订单状态中文映射
    orderStatusText: () => (status) => {
      const statusMap = {
        'pending': '待付款',
        'paid': '待发货',
        'shipped': '待收货',
        'completed': '已完成',
        'cancelled': '已取消',
        'refunded': '已退款'
      }
      return statusMap[status] || status
    }
  },
  
  actions: {
    async createOrder(orderData) {
      this.isLoading = true
      this.error = null
      try {
        const response = await api.createOrder(orderData)
        // 创建订单后清空已选中的购物车商品
        const cartStore = useCartStore()
        cartStore.removeSelectedItems()
        ElMessage.success('订单创建成功')
        return response.data
      } catch (error) {
        this.error = error.message
        ElMessage.error('订单创建失败')
        throw error
      } finally {
        this.isLoading = false
      }
    },
    
    async getOrders(params = {}) {
      this.isLoading = true
      try {
        const response = await api.getOrderList(params)
        this.orders = response.data.list || []
        return response.data
      } catch (error) {
        ElMessage.error('获取订单列表失败')
        throw error
      } finally {
        this.isLoading = false
      }
    },
    
    async getSellerOrders(params = {}) {
      this.isLoading = true
      try {
        const response = await api.getSellerOrders(params)
        this.sellerOrders = response.data.list || []
        return response.data
      } catch (error) {
        ElMessage.error('获取销售订单失败')
        throw error
      } finally {
        this.isLoading = false
      }
    },
    
    async getOrderById(id) {
      this.isLoading = true
      try {
        const response = await api.getOrderDetail(id)
        this.currentOrder = response.data
        return response.data
      } catch (error) {
        ElMessage.error('获取订单详情失败')
        throw error
      } finally {
        this.isLoading = false
      }
    },
    
    async cancelOrder(orderId) {
      try {
        const response = await api.cancelOrder(orderId)
        // 更新本地订单状态
        this.updateLocalOrderStatus(orderId, 'cancelled')
        ElMessage.success('订单已取消')
        return response.data
      } catch (error) {
        ElMessage.error('取消订单失败')
        throw error
      }
    },
    
    async confirmReceipt(orderId) {
      try {
        const response = await api.confirmReceipt(orderId)
        // 更新本地订单状态
        this.updateLocalOrderStatus(orderId, 'completed')
        ElMessage.success('确认收货成功')
        return response.data
      } catch (error) {
        ElMessage.error('确认收货失败')
        throw error
      }
    },
    
    async shipOrder(orderId, logisticsData) {
      try {
        const response = await api.shipOrder(orderId, logisticsData)
        // 更新本地订单状态
        this.updateLocalOrderStatus(orderId, 'shipped')
        ElMessage.success('发货成功')
        return response.data
      } catch (error) {
        ElMessage.error('发货失败')
        throw error
      }
    },
    
    async reviewOrder(orderId, reviewData) {
      try {
        const response = await api.reviewOrder(orderId, reviewData)
        ElMessage.success('评价成功')
        return response.data
      } catch (error) {
        ElMessage.error('评价失败')
        throw error
      }
    },
    
    // 更新本地订单状态
    updateLocalOrderStatus(orderId, status) {
      // 更新买家订单
      const orderIndex = this.orders.findIndex(o => o.id === orderId)
      if (orderIndex !== -1) {
        this.orders[orderIndex].status = status
        this.orders[orderIndex].updatedAt = new Date().toISOString()
      }
      
      // 更新卖家订单
      const sellerOrderIndex = this.sellerOrders.findIndex(o => o.id === orderId)
      if (sellerOrderIndex !== -1) {
        this.sellerOrders[sellerOrderIndex].status = status
        this.sellerOrders[sellerOrderIndex].updatedAt = new Date().toISOString()
      }
      
      // 更新当前订单
      if (this.currentOrder && this.currentOrder.id === orderId) {
        this.currentOrder.status = status
        this.currentOrder.updatedAt = new Date().toISOString()
      }
    }
  }
})